package de.dopichaj.labrador.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.BoxLayout;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.OverlayLayout;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public final class GraphCanvas extends JPanel {

    private static final long serialVersionUID = 1L;
    
    private final Map<String, Map<String, Graph>> graphs =
        new HashMap<String, Map<String, Graph>>();
    private final JPanel canvas;
    private final JList list;
    
    private String topic = "";
    private final Map<String, Boolean> runEnabled = new HashMap<String, Boolean>();
    
    private static final Color[] colors = new Color[] { Color.RED, Color.GREEN,
        Color.BLUE, Color.MAGENTA, Color.BLACK };

    public GraphCanvas(Map<Integer, Map<String, double[]>> dataMap) {
        
        setLayout(new BorderLayout());
        
        canvas = new JPanel();
        canvas.setBackground(Color.WHITE);
        add(canvas, BorderLayout.CENTER);
        canvas.setLayout(new OverlayLayout(canvas));
        
        final JPanel leftPart = new JPanel();
        add(leftPart, BorderLayout.SOUTH);
        leftPart.setBackground(Color.WHITE);
        leftPart.setLayout(new BoxLayout(leftPart, BoxLayout.Y_AXIS));
        
        boolean firstTime = true;
        final Map<String, double[]> avgMap = new HashMap<String, double[]>();
        for (final int topic : dataMap.keySet()) {
            final HashMap<String, Graph> map = new HashMap<String, Graph>();
            graphs.put(String.valueOf(topic), map);
            int colIndex = 0;
            final List<String> runs = new ArrayList<String>(dataMap.get(topic).keySet());
            Collections.sort(runs);
            for (final String file : runs) {
                final Color color = colors[colIndex % colors.length];
                final double[] data = dataMap.get(topic).get(file);
                final Graph graph = new Graph(color, data);
                map.put(file, graph);
                
                if (firstTime) {
                    
                    final double[] avgData = new double[data.length];
                    avgMap.put(file, avgData);
                    
                    leftPart.add(makeToggleButton(file, color));
                    runEnabled.put(file, true);
                }
                final double[] avgData = avgMap.get(file);
                for (int i = 0; i < data.length; i++) {
                    avgData[i] += data[i];
                }

                colIndex++;
            }
            firstTime = false;
        }
        
        // normalize the average data
        int colIndex = 0;
        final Map<String, Graph> avgGraphMap = new HashMap<String, Graph>();
        for (final Entry<String, double[]> entry : avgMap.entrySet()) {
            final double[] avgData = entry.getValue();
            for (int i = 0; i < avgData.length; i++) {
                avgData[i] /= graphs.size();
            }
            avgGraphMap.put(entry.getKey(),
                new Graph(colors[colIndex % colors.length], avgData));
            colIndex++;
        }
        graphs.put("avg", avgGraphMap);

        // create the list
        final String[] labels = graphs.keySet().toArray(new String[0]);
        Arrays.sort(labels);
        list = new JList(labels);
        list.addListSelectionListener(new ListListener());
        add(new JScrollPane(list), BorderLayout.EAST);
    }

    private JToggleButton makeToggleButton(final String file, final Color color) {
        final JToggleButton button = new JToggleButton(file);
        button.setForeground(color);
        button.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                runEnabled.put(file, !runEnabled.get(file));
                redrawGraphs();
            }});
        return button;
    }

    private final class ListListener implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                final int selectedIndex = list.getSelectedIndex();
                if (selectedIndex != -1) {
                    topic = (String)list.getModel().getElementAt(selectedIndex);
                    redrawGraphs();
                }
            }
        }
    }

    private static final class MyBackground extends JPanel {
        
        private static final long serialVersionUID = 1L;
        private static final int STRIPES = 10;
        private static final Color[] colors = new Color[] { Color.WHITE, new Color(240, 240, 240) };
        @Override
        public void paint(Graphics g) {
            
            final double stripeHeight = (double)getHeight() / STRIPES;
            for (int i = 0; i < STRIPES; i++) {
                g.setColor(colors[i%2]);
                final int y1 = (int)(i * stripeHeight);
                final int y2 = (int)((i+1) * stripeHeight);
                //g.fillRect(0, y1, getWidth(), y2);
            }
            
            final double xScale = (double)getWidth() / Math.log(1500);
            
            for (int i = 10; i < 1500; i += 10) {
                g.setColor(colors[i%2]);
                g.fillRect((int)(Math.log(i) * xScale), 0, (int)(Math.log(i+10) * xScale), getHeight());
            }
        }
    }
    
    private void redrawGraphs() {
        canvas.removeAll();
        final Map<String, Graph> map = graphs.get(topic);
        if (map != null) {
            Graph first = null;
            for (final String run : map.keySet()) {
                if (runEnabled.get(run)) {
                    final Graph graph = map.get(run);
                    canvas.add(graph);
                    graph.setVisible(true);

                    if (first == null) {
                        first = graph;
                    } else {
                        final double[] firstData = first.getData();
                        final double[] secondData = graph.getData();
                        final double[] diffData = new double[firstData.length];
                        for (int i = 0; i < firstData.length; i++) {
                            diffData[i] = (firstData[i] - secondData[i] + 1) / 2;
                        }
                        canvas.add(new Graph(Color.ORANGE, diffData));
                    }
                }
            }
            canvas.add(new MyBackground());
            canvas.validate();
            repaint();
        }
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/